package com.msc.cili.web.admincontroller.accountcontroller;


import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.msc.cili.common.api.Result;
import com.msc.cili.security.utils.JwtUtils;
import com.msc.cili.service.user.UserService;
import com.msc.cili.service.user.bo.UserInfoBo;
import com.msc.cili.web.admincontroller.accountcontroller.param.LoginDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 骑蜗牛的羊
 * @date 2023/4/17 23:07
 * <p></p>
 */
@Slf4j
@RestController
public class AccountController {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    private UserService userService;

    @GetMapping("/api/v1/acc/test2")
    public String export() {
        System.out.println("进入acc方法了");
        return "22222";
    }

    /**
     * 登录请求处理
     */
    @CrossOrigin
    @PostMapping("/api/v1/acc/login")
    public Result login(HttpServletResponse response) {

        return Result.succ(null);
    }

    /**
     * 登录请求处理
     */
    @CrossOrigin
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        final UserInfoBo user = userService.getUserInfoByUserName(loginDto.getUsername());
        Assert.notNull(user, "用户名或密码错误");
        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("用户名或密码错误！");
        }
        if (user.getStatus() == 0) {
            return Result.fail("账户已被禁用");
        }
        String jwt = jwtUtils.generateToken(user.getId(), user.getUsername());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");
        // 用户可以另一个接口 暂时禁用账号密码登录
//        return Result.succ(MapUtil.builder()
//                .put("id", user.getId())
//                .put("username", user.getUsername())
//                .put("avatar", user.getAvatar())
//                .put("email", user.getEmail())
//                .put("role", user.getRole())
//                .map()
//        );
        return Result.succ(jwt);
    }

    /**
     * 登出请求处理
     */
    @GetMapping("/logout")
    @RequiresAuthentication
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ("退出成功");
    }

}
